import Vue from 'vue'
import { getDeviceInfo } from '@/api/login'

/**
 * 获取Authorization
 * @returns
 */
export const getAccessToken = () => {
  return new Promise((resolve) => {
    const store = Vue.prototype._store
    const { user } = store.state
    if (user) {
      const { accessToken } = user
      resolve(`Bearer ${accessToken}`)
    } else {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }
  })
}

/**
 * 获取refreshToken
 * @returns
 */
export const getRefreshToken = () => {
  return new Promise((resolve) => {
    const store = Vue.prototype._store
    const { user } = store.state
    if (user) {
      const { refreshToken } = user
      resolve(refreshToken)
    } else {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }
  })
}

/**
 * 获取设备序列号
 * @returns
 */
export const getSerialNo = () => {
  return new Promise(async (resolve) => {
    const store = Vue.prototype._store
    const {
      user: { serialNo: cacheSerialNo }
    } = store.state

    if (cacheSerialNo) {
      resolve(cacheSerialNo)
      return
    }

    const serialNo = 'NKQF4PDU7L'
    store.commit('setSerialNo', serialNo)
    resolve(serialNo)
  })
}

/**
 * 获取TenantId
 * @returns
 */
export const getTenantId = () => {
  return new Promise(async (resolve) => {
    const store = Vue.prototype._store
    const {
      user: { tenantId: cacheTenantId }
    } = store.state

    if (cacheTenantId) {
      resolve(cacheTenantId)
      return
    }

    const {
      data: { tenantId }
    } = await getDeviceInfo({
      serialNo: '435f2aef50ec60a5'
    })
    store.commit('setTenantId', tenantId)
    resolve(tenantId)
  })
}
